package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private  RabbitTemplate rabbitTemplate;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void deductStock(List<OrderDetailDTO> items) {
        String sqlStatement = "com.hmall.item.mapper.ItemMapper.updateStock";
        boolean r = false;
        try {
            r = executeBatch(items, (sqlSession, entity) -> sqlSession.update(sqlStatement, entity));
            
        } catch (Exception e) {
            log.error("更新库存异常", e);
            throw new BizIllegalException("库存不足！");
        }
        if (!r) {
            throw new BizIllegalException("库存不足！");
        }
    }

    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }

    /*
     * 更新商品状态
     * */
    @Override
    public void updateItemStatus(Long id, Integer status) {
        //更新商品状态
        lambdaUpdate().set(Item::getStatus, status).eq(Item::getId, id).update();

        //发送MQ消息
        String routingKey = status == 1 ? MqConstants.ITEM_UP_KEY : MqConstants.ITEM_DOWN_KEY;
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE_NAME, routingKey, id);
    }

    @Override
    public List<ItemDTO> queryItemByIdsCache(Collection<Long> ids) {
        //返回列表
        List<ItemDTO> itemDTOList = new ArrayList<>();
        for (Long id : ids) {
            //从缓存中获取数据
            Item item = (Item)redisTemplate.opsForValue().get("hmall:item:"+ id);
            if(item != null){
                //有数据，直接添加到列表中
                itemDTOList.add(BeanUtils.copyBean(item, ItemDTO.class));
            }else{
                //无数据，从数据库中查询
                Item itemDB = getById(id);
                if(itemDB != null){
                    //添加到缓存中
                    redisTemplate.opsForValue().set("hmall:item:"+ id, itemDB);
                    //添加到列中
                    itemDTOList.add(BeanUtils.copyBean(itemDB, ItemDTO.class));
                }
            }
        }
        return itemDTOList;
    }
}
